package com.tgy.topk;

import com.tgy.heap.BinaryHeap;

import java.util.Comparator;
import java.util.PriorityQueue;

/**
 * @Author: tgy
 * @Date: 2020-10-19 16:53
 */
public class TopKHeap {

    private Integer[] elements;

    private int k;


    public int topK(Integer[] elements, int k) {

        BinaryHeap<Integer> binaryHeap = new BinaryHeap<>(new Comparator<Integer>() {
            @Override
            public int compare(Integer o1, Integer o2) {
                return o2-o1;
            }
        });

        for (Integer element : elements) {

            if (binaryHeap.size() < k) {

                binaryHeap.add(element);
            }else {

                if (binaryHeap.get() < element) {

                    binaryHeap.replace(element);
                }
            }
        }

        return binaryHeap.get();
    }

}
